cat('\n\nCreating Table A21 \n\n')

##modified clustered standard error function for use below
clx <-  function(fm, dfcw, cluster){
  library(sandwich)
  library(lmtest)
  M <- length(unique(cluster))
  N <- length(cluster)
  dfc <- (M/(M-1))*((N-1)/(N-fm$rank))
  u <- apply(estfun(fm),2,
             function(x) tapply(x, cluster, sum))
  vcovCL <- dfc*sandwich(fm, meat=crossprod(u)/N)*dfcw
  coeftest(fm, vcovCL) 
  }


dat  = read.csv('TableA21_data.csv')
tests.matrix = matrix(nrow = 6, ncol = 11)

for(i in 1:5){
  use.dat = dat[dat$test == i,]
  fm = lm(diff~1, data = use.dat)
  tests.matrix[i,1] = mean(use.dat$intsTsum - use.dat$intsSsum)
  tests.matrix[i,2] = sd(use.dat$intsTsum - use.dat$intsSsum)
  tests.matrix[i,3] = mean(use.dat$segsTsum - use.dat$segsSsum)
  tests.matrix[i,4] = sd(use.dat$segsTsum - use.dat$segsSsum)
  tests.matrix[i,5] = summary(fm)$coefficients[1,'Estimate']
  tests.matrix[i,6] = summary(fm)$coefficients[1,'Std. Error']
  tests.matrix[i,7] = summary(fm)$coefficients[1,'t value']
  tests.matrix[i,8] = summary(fm)$coefficients[1,'Estimate'] - 1.96*summary(fm)$coefficients[1,'Std. Error'] 
  tests.matrix[i,9] = summary(fm)$coefficients[1,'Estimate'] + 1.96*summary(fm)$coefficients[1,'Std. Error'] 
  tests.matrix[i,10] = summary(fm)$coefficients[1,'Pr(>|t|)']/2
  tests.matrix[i,11] = nrow(use.dat)
  }
  
##pooled results
fm = lm(diff~1, data = dat)
lm.test = clx(fm,1,dat$test)


tests.matrix[6,1] = mean(dat$intsDif)
tests.matrix[6,2] = sd(dat$intsDif)
tests.matrix[6,3] = mean(dat$segsDif)
tests.matrix[6,4] = sd(dat$segsDif)
tests.matrix[6,5] = lm.test[,'Estimate']
tests.matrix[6,6] = lm.test[,'Std. Error']
tests.matrix[6,7] = lm.test[,'t value']
tests.matrix[6,8] = lm.test[,'Estimate'] - (1.96 * lm.test[,'Std. Error'])
tests.matrix[6,9] = lm.test[,'Estimate'] + (1.96 * lm.test[,'Std. Error'])
tests.matrix[6,10] = lm.test[,'Pr(>|t|)']/2
tests.matrix[6,11] = nrow(dat)


tests.matrix = as.data.frame(round(tests.matrix,2))
tests.matrix[,1] = paste(tests.matrix[,1], ' (',tests.matrix[,2],')',sep='')
tests.matrix[,3] = paste(tests.matrix[,3], ' (',tests.matrix[,4],')',sep='')
tests.matrix[,5] = paste(tests.matrix[,5], ' (',tests.matrix[,6],')',sep='')
tests.matrix[,8] = paste('[',tests.matrix[,8],',',tests.matrix[,9],']',sep='')

tests.matrix[,9] = NULL
tests.matrix[,6] = NULL
tests.matrix[,4] = NULL
tests.matrix[,2] = NULL

colnames(tests.matrix)= c('Integrated (SD)','Segregated (SD)','Difference (SE)', 'T value',
                               'CI','p','N')


out.table = xtable(tests.matrix,
                        digits = 2)

print(out.table,
      file = "TableA21.tex",
      floating = F,
      booktabs = T)